package com.xu.common.domain;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import org.springframework.util.CollectionUtils;

import java.io.Serial;
import java.io.Serializable;
import java.util.List;

/**
 * 分页查询响应对象
 *
 * @author xu
 * 2022/7/26 11:46
 */
@Data
public class TableDataInfo<T> implements Serializable {
    @Serial
    private static final long serialVersionUID = 1L;

    /**
     * 总记录数
     */
    private long total;

    /**
     * 列表数据
     */
    private List<T> rowList;

    /**
     * 消息状态码
     */
    private int code;

    /**
     * 消息内容
     */
    private String msg;

    public static <T> TableDataInfo<T> build(IPage<T> page) {
        TableDataInfo<T> rspData = new TableDataInfo<>();
        rspData.setCode(HttpStatus.HTTP_OK);
        rspData.setMsg("查询成功");
        rspData.setRowList(page.getRecords());
        rspData.setTotal(page.getTotal());
        return rspData;
    }

    public static <C,T> TableDataInfo<C> build(IPage<T> page,Class<C> tClass){
        IPage<C> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        List<T> tList = page.getRecords();
        if(CollectionUtils.isEmpty(tList)){
            return build(voPage);
        }
        List<C> toList = BeanUtil.copyToList(tList, tClass);
        voPage.setRecords(toList);
        return build(voPage);
    }
}
